package com.example.springbott.wx_service;

import com.example.springbott.bean.*;
import com.example.springbott.bean.common.BasePageInfo;
import com.example.springbott.bean.common.CommonData;
import com.example.springbott.mapper.MarketCartMapper;
import com.example.springbott.wx_bean_zhu.WxMyListCouponVo;
import com.example.springbott.mapper.MarketCouponMapper;
import com.example.springbott.mapper.MarketCouponUserMapper;
import com.example.springbott.wx_bean_zhu.WxCouponUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author: 小朱
 * @Description:只有接口关于list的才需要使用分页功能，pageInf
 * @date: 11:36 2022/11/22
 */
@Service
public class WxCouponServiceImpl implements WxCouponService {
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCartMapper marketCartMapper;
    //-----------------------小朱------------------------

    /**
     * @author: 小朱
     * @Description:个人中心的查询功能
     * @date: 15:12 2022/11/22
     */
    @Override
    public CommonData wxCouponMylist(Short status, Integer page, Integer limit) {
        // PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        // MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        // MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
        // //与前端传过来的status做比较
        // MarketUser principal = (MarketUser) SecurityUtils.getSubject().getPrincipal();
        // criteria.andStatusEqualTo(status).andUserIdEqualTo(principal.getId());
        // //与数据库CouponUser连接
        // List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        // //与数据库couponUser相连
        // MarketCouponExample marketCouponExample = new MarketCouponExample();
        // List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        // //将marketCoupon里面的需要的八个变量，封装到新的对象中
        // //新建的wxCouponUser对象的集合list
        // ArrayList<WxCouponUser> wxCouponUsers = new ArrayList<>();
        // //增强for，不用在里面写get方法
        //
        //
        // for (MarketCoupon marketCoupon : marketCoupons) {
        //     WxCouponUser wxCouponUser = new WxCouponUser();
        //     //取出来
        //     //原来的available(即为delete)
        //     wxCouponUser.setId(marketCoupon.getId());
        //     wxCouponUser.setDesc(marketCoupon.getDesc());
        //     wxCouponUser.setDiscount(marketCoupon.getDiscount());
        //     wxCouponUser.setEndTime(marketCoupon.getEndTime());
        //     wxCouponUser.setMin(marketCoupon.getMin());
        //     wxCouponUser.setName(marketCoupon.getName());
        //     wxCouponUser.setTag(marketCoupon.getTag());
        //     wxCouponUser.setDeleted(false);
        //     //再加原来的status和cid
        //     wxCouponUser.setStatus(status);
        //     wxCouponUser.setCid(principal.getId());
        //     //将对象逐个添加为list集合
        //     wxCouponUsers.add(wxCouponUser);
        // }
        // //分页功能
        // PageInfo<WxCouponUser> wxCouponUserPageInfo = new PageInfo<>(wxCouponUsers);
        // return CommonData.data(wxCouponUserPageInfo);
//-----------------------------------------------------------------------------------------------
        //获取当前登录用户的对象和id
        MarketUser principal = (MarketUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = principal.getId();
        //分页功能
        PageHelper.startPage(page, limit);
        //新建一个优惠券用户的条件实例对象
        MarketCouponUserExample example = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false).andStatusEqualTo(status).andUserIdEqualTo(userId);
        //根据添加的时间排序，降序
        example.setOrderByClause("add_time" + " " + "desc");
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example);
        if (marketCouponUsers.size() == 0) {
            return null;
        }
        ArrayList<Integer> couponIds = new ArrayList<>();
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            couponIds.add(marketCouponUser.getCouponId());
        }
        //新建一个后端的集合，用来接收从数据库传过来的一个一个marketCouponUser对象,包装数据
        List<WxMyListCouponVo> wxMyListCouponVos = new ArrayList<>();

        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria1 = marketCouponExample.createCriteria();
        //in在sql语句中，表示同类型的多个数据
        criteria1.andDeletedEqualTo(false).andIdIn(couponIds);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            WxMyListCouponVo wxMyListCouponVo = new WxMyListCouponVo();
            for (MarketCoupon marketCoupon : marketCoupons) {
                Integer cid = marketCouponUser.getCouponId();
                Integer id = marketCoupon.getId();
                //判断优惠表的id和优惠用户记录表的id是否相等，以相等为两个表的连接条件
                if (!id.equals(cid)) {
                    continue;
                }
                wxMyListCouponVo.setName(marketCoupon.getName());
                wxMyListCouponVo.setDesc(marketCoupon.getDesc());
                wxMyListCouponVo.setMin(marketCoupon.getMin());
                wxMyListCouponVo.setTag(marketCoupon.getTag());
                wxMyListCouponVo.setDiscount(marketCoupon.getDiscount());
                wxMyListCouponVo.setId(marketCouponUser.getId());
                wxMyListCouponVo.setCid(marketCouponUser.getCouponId());
                wxMyListCouponVo.setStartTime(marketCouponUser.getStartTime());
                wxMyListCouponVo.setEndTime(marketCouponUser.getEndTime());
                wxMyListCouponVo.setAvailable(false);
                break;
            }
            wxMyListCouponVos.add(wxMyListCouponVo);

        }
        PageInfo pageInfo = new PageInfo(wxMyListCouponVos);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();
        CommonData<WxMyListCouponVo> wxMyListCouponVoCommonData = new CommonData<>();
        wxMyListCouponVoCommonData.setTotal((int) total);
        wxMyListCouponVoCommonData.setPages(pages);
        wxMyListCouponVoCommonData.setPage(page);
        wxMyListCouponVoCommonData.setLimit(limit);
        wxMyListCouponVoCommonData.setList(wxMyListCouponVos);
        return wxMyListCouponVoCommonData;

    }


    /**
     * @author: 小朱
     * @Description:查询功能
     * @date: 21:10 2022/11/22
     */
    @Override
    public CommonData wxCouponList(MarketCoupon marketCoupon, BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        //Coupons集合根据分页限制返回限定数量的对象给前端
        PageInfo<MarketCoupon> marketCouponPageInfo = new PageInfo<>(marketCoupons);
        long total = marketCouponPageInfo.getTotal();
        int limit = marketCouponPageInfo.getSize();
        int pages = marketCouponPageInfo.getPages();
        int page = marketCouponPageInfo.getPageNum();
        CommonData commonData = new CommonData();
        commonData.setList(marketCoupons);
        commonData.setLimit(limit);
        commonData.setPage(page);
        commonData.setPages(pages);
        commonData.setTotal((int) total);

        return commonData;
    }

    /**
     * @param
     * @author: 小朱
     * @Description:receive , 新增优惠券, 将主页的优惠券增加到个人中心
     * @date: 9:31 2022/11/23
     */
    @Override
    public MarketCouponUser wxCouponReceive(Integer couponId) {
        //获取当前登录用户的对象以及id
        MarketUser principal = (MarketUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = principal.getId();
        //新建一个marketCouponUser对象，用来封装需要的变量
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        //新建条件对象,用来获取前端发过来的优惠券id
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        criteria.andIdEqualTo(couponId);
        //与数据库连接
        //int i = marketCouponMapper.insertSelective(marketCouponExample.createCriteria().andIdEqualTo(couponId.));
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        MarketCoupon marketCoupon = marketCoupons.get(0);

        marketCouponUser.setAddTime(new Date());
        marketCouponUser.setUpdateTime(new Date());
        marketCouponUser.setDeleted(false);
        marketCouponUser.setCouponId(marketCoupon.getId());
        marketCouponUser.setStatus(marketCoupon.getStatus());
        //usetime,orderid没有,
        //marketCouponUser的id是自增的，不用管他
        marketCouponUser.setStartTime(new Date());
        Short days = marketCoupon.getDays();
        Date endDate = new Date(System.currentTimeMillis() + days * 24 * 60 * 60 * 1000);


        marketCouponUser.setEndTime(endDate);
        //将当前登录用户的id封装进marketCouponUser对象中
        marketCouponUser.setUserId(userId);

        marketCouponUserMapper.insertSelective(marketCouponUser);
        return marketCouponUser;
    }

    /**
     * @author: 小朱
     * @Description: exchange  兑换优惠券的优惠码
     * 不需要返回值，因为“兑换”后，只会提示兑换是否成功，列表展示添加的优惠券是另外一个接口(mylist)要做的事情
     * @date: 15:45 2022/11/23
     */
    @Override
    public Integer wxCouponExchange(String code) {
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        criteria.andCodeEqualTo(code).andStatusEqualTo((short) 0).andDeletedEqualTo(false);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        if (marketCoupons.size() == 0) {
            return 0;
        } else {
            //新增的代码
            MarketCoupon marketCoupon = marketCoupons.get(0);
            MarketUser principal = (MarketUser) SecurityUtils.getSubject().getPrincipal();
            Integer userId = principal.getId();

            MarketCouponUser marketCouponUser = new MarketCouponUser();
            marketCouponUser.setUserId(userId);
            marketCouponUser.setCouponId(marketCoupon.getId());
            marketCouponUser.setStatus((short) 0);
            marketCouponUser.setUsedTime(null);
            marketCouponUser.setStartTime(new Date());
            marketCouponUser.setEndTime(null);
            marketCouponUser.setOrderId(null);
            marketCouponUser.setAddTime(new Date());
            marketCouponUser.setUpdateTime(new Date());
            Date endDate = new Date(System.currentTimeMillis() + marketCoupon.getDays() * 24 * 60 * 60 * 1000);
            marketCouponUser.setDeleted(false);
            marketCouponUser.setEndTime(endDate);

            marketCouponUserMapper.insertSelective(marketCouponUser);
            return 1;
        }


    }





    /**
     * @author: 小朱
     * @Description: 订单模块里面的优惠券选择
     * @date: 21:05 2022/11/23
     */
    @Override
    public CommonData wxCouponSelectlist(Integer cartId) {
        MarketUser principal = (MarketUser) SecurityUtils.getSubject().getPrincipal();
        int userid = principal.getId().intValue();
        if (cartId==0){
            //查询订单的总金额
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andCheckedEqualTo(true);
            criteria.andUserIdEqualTo(userid);
            List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
            int TotalPrice=0;

            for (int i = 0; i < marketCartList.size(); i++) {
                MarketCart marketCart = marketCartList.get(i);
               TotalPrice+= marketCart.getNumber()*marketCart.getPrice().intValue();
            }
            //查询用户拥有的优惠券
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria marketCouponUserExampleCriteria = marketCouponUserExample.createCriteria();
            marketCouponUserExampleCriteria.andDeletedEqualTo(false);
            marketCouponUserExampleCriteria.andUserIdEqualTo(userid);
            marketCouponUserExampleCriteria.andStartTimeLessThan(new Date());
            marketCouponUserExampleCriteria.andEndTimeGreaterThan(new Date());
            marketCouponUserExampleCriteria.andStatusEqualTo((short)0);
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            List<Map> maps = new ArrayList<>();
            for (int i = 0; i < marketCouponUsers.size(); i++) {
                MarketCouponUser marketCouponUser = marketCouponUsers.get(i);
                Map<String, Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("available",true);
                stringObjectMap.put("cid",marketCouponUser.getCouponId());
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());
                stringObjectMap.put("desc",marketCoupon.getDesc());
                stringObjectMap.put("discount",marketCoupon.getDiscount());
                stringObjectMap.put("endTime",marketCouponUser.getStartTime());
                stringObjectMap.put("id",marketCouponUser.getId());
                stringObjectMap.put("min",marketCoupon.getMin());
                stringObjectMap.put("name",marketCoupon.getName());
                stringObjectMap.put("tag",marketCoupon.getTag());
                if (TotalPrice<marketCoupon.getMin().intValue()){
                    stringObjectMap.put("available",false);
                }
                maps.add(stringObjectMap);
            }
            PageInfo<Map> mapPageInfo = new PageInfo<>(maps);
        return     CommonData.data(mapPageInfo);
        }else {
            MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartId);
            int TotalPrice=0;
            TotalPrice+= marketCart.getNumber()*marketCart.getPrice().intValue();
            //查询用户拥有的优惠券
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria marketCouponUserExampleCriteria = marketCouponUserExample.createCriteria();
            marketCouponUserExampleCriteria.andDeletedEqualTo(false);
            marketCouponUserExampleCriteria.andUserIdEqualTo(userid);
            marketCouponUserExampleCriteria.andStartTimeLessThan(new Date());
            marketCouponUserExampleCriteria.andEndTimeGreaterThan(new Date());
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            List<Map> maps = new ArrayList<>();
            for (int i = 0; i < marketCouponUsers.size(); i++) {
                MarketCouponUser marketCouponUser = marketCouponUsers.get(i);
                Map<String, Object> stringObjectMap = new HashMap<>();
                stringObjectMap.put("available",true);
                stringObjectMap.put("cid",marketCouponUser.getCouponId());
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());
                stringObjectMap.put("desc",marketCoupon.getDesc());
                stringObjectMap.put("discount",marketCoupon.getDiscount());
                stringObjectMap.put("endTime",marketCouponUser.getStartTime());
                stringObjectMap.put("id",marketCouponUser.getId());
                stringObjectMap.put("min",marketCoupon.getMin());
                stringObjectMap.put("name",marketCoupon.getName());
                stringObjectMap.put("tag",marketCoupon.getTag());
                if (TotalPrice<marketCoupon.getMin().intValue()){
                    stringObjectMap.put("available",false);
                }
                maps.add(stringObjectMap);
            }
            PageInfo<Map> mapPageInfo = new PageInfo<>(maps);
            return     CommonData.data(mapPageInfo);

        }

    }
}
